#include "GameManager.h"
#include "Utils.h"
#include "GamePlayLayer.h"

#define VERIFY_NUMBER 555

GameManager* GameManager::instance = 0;

GameManager::GameManager()
{
	loadHighScore();
	score = 0;
	visibleSize = CCDirector::sharedDirector()->getVisibleSize();
	groundY = 0;
	gamePlayLayer = 0;
}

GameManager::~GameManager()
{
}

GameManager* GameManager::getInstance(){
	if(instance == 0){
		instance = new GameManager();
	}
	return instance;
}

void GameManager::loadHighScore(){
	int checkValue = -1;
	int encypted = CCUserDefault::sharedUserDefault()->getIntegerForKey(HIGH_SCORE_KEY, -1);
	int checkValueEncrypted = CCUserDefault::sharedUserDefault()->getIntegerForKey(HIGH_SCORE_CHECK_KEY, -1);

	if(encypted != -1){
		Utils::xcrypt((char*)&encypted, sizeof(int), (char*)&highScore, ENCRYPT_KEY);
		Utils::xcrypt((char*)&checkValueEncrypted, sizeof(int), (char*)&checkValue, ENCRYPT_KEY);
		if(highScore + VERIFY_NUMBER != checkValue){
			highScore = 0;
		}
	}
	else{
		highScore = 0;
	}
}

void GameManager::saveHighScore(int highScore){
	this->highScore = highScore;

	// save to user default
	int encypted = -1;
	int checkNumberEncrypted = -1;
	int checkNumber = highScore + VERIFY_NUMBER;

	Utils::xcrypt((char*)&highScore, sizeof(int), (char*)&encypted, ENCRYPT_KEY);
	Utils::xcrypt((char*)&checkNumber, sizeof(int), (char*)&checkNumberEncrypted, ENCRYPT_KEY);

	CCUserDefault::sharedUserDefault()->setIntegerForKey(HIGH_SCORE_KEY, encypted);
	CCUserDefault::sharedUserDefault()->setIntegerForKey(HIGH_SCORE_CHECK_KEY, checkNumberEncrypted);
}

void GameManager::resetGame(){
	score = 0;
}